package com.gpframework.module.ctn.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpframework.common.config.GpframeworkConfig;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.module.ctn.domain.GpReceiptGoods;
import com.gpframework.module.ctn.domain.GpSackInformation;
import com.gpframework.module.ctn.domain.vo.GpCtnOrderExcel;
import com.gpframework.module.ctn.domain.vo.GpSackInformationExcel;
import com.gpframework.module.ctn.domain.vo.GpSackInformationVo;
import com.gpframework.module.ctn.mapper.GpSackInformationMapper;
import com.gpframework.module.ctn.service.IGpReceiptGoodsService;
import com.gpframework.module.ctn.service.IGpSackInformationService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName GpSackInformation
 * @Author gpframework
 * @Date 2024-02-28
 * @Version 1.0.0
 * @Description 散货信息填写Service业务层处理
 */
@Service
public class GpSackInformationServiceImpl extends ServiceImpl<GpSackInformationMapper, GpSackInformation> implements IGpSackInformationService {

    @Autowired
    private IGpReceiptGoodsService iGpReceiptGoodsService;
    @Autowired
    private IGpSackInformationService iGpSackInformationService;

    /**
     * @Description 查询列表返回VO 用于返回给前端的列表接口
     * @Author gpframework
     * @Date 2024-02-28
     * @Param [lqw]
     * @Return List<GpSackInformationVo>
     */
    @Override
    public List<GpSackInformationVo> listVo(QueryWrapper<GpSackInformation> lqw) {
        return this.baseMapper.listVo(lqw);
    }

    @Override
    public List<GpSackInformationVo> listVoed(QueryWrapper<GpSackInformation> lqw) {
        return this.baseMapper.listVoed(lqw);
    }

    /**
     * @Description 通过查询详情VO 用于返回给前端的列详情接口
     * @Author gpframework
     * @Date 2024-02-28
     * @Param [id]
     * @Return GpSackInformationVo
     */
    @Override
    public GpSackInformationVo getVoById(Long id) {
        return this.baseMapper.getVo(id);
    }

    @Override
    public List<GpSackInformationExcel> gpSackInformationImport(List<GpSackInformationExcel> excelList, Long brandId, Long storeId) {
        //导入失败的列表
        List<GpSackInformationExcel> failureList = new ArrayList<>();
        //散货信息填写
        GpSackInformation gpSackInformation;

        for (int i = 0; i < excelList.size(); i++) {
            GpSackInformationExcel excel = excelList.get(i);
            if (StringUtils.isNull(excel)) {
                excel = new GpSackInformationExcel();
                excel.setSubscript(i+1);
                excel.setMsg("读取数据失败");
                failureList.add(excel);
                continue;
            }
            gpSackInformation = Convert.convert(new TypeReference<GpSackInformation>() {}, excel);
            this.save(gpSackInformation);
        }
        return failureList;
    }

    @Override
    public Boolean updateBatch(GpReceiptGoods gpReceiptGoodsUpdate) {
        List<GpSackInformation> gpSackInformationList = gpReceiptGoodsUpdate.getGpSackInformationUpdate().getGpSackInformationList();
        if (StringUtils.isNotEmpty(gpSackInformationList)){
            for (GpSackInformation sackInformation : gpSackInformationList) {
                GpSackInformation gpSackInformation = Convert.convert(new TypeReference<GpSackInformation>() {}, sackInformation);
                GpReceiptGoods gpReceiptGoods = iGpReceiptGoodsService.getById(sackInformation.getReceiptId());
                if (gpReceiptGoods!=null){
                    //复制订单信息
                    gpSackInformation.setGoodsDescription(gpReceiptGoodsUpdate.getGoodsDescription());
                    gpSackInformation.setReceiptId(gpReceiptGoodsUpdate.getId());
                    gpSackInformation.setReceiptNo(gpReceiptGoodsUpdate.getReceiptNo());
                    gpSackInformation.setReceiptDate(gpReceiptGoodsUpdate.getReceiptDate());
                    iGpSackInformationService.updateById(gpSackInformation);
                }else {
                    gpSackInformation.setGoodsDescription(gpReceiptGoodsUpdate.getGoodsDescription());
                    gpSackInformation.setReceiptId(gpReceiptGoodsUpdate.getId());
                    gpSackInformation.setReceiptNo(gpReceiptGoodsUpdate.getReceiptNo());
                    gpSackInformation.setReceiptDate(gpReceiptGoodsUpdate.getReceiptDate());
                    gpSackInformation.setSupplier(gpReceiptGoodsUpdate.getSupplier());
                    gpSackInformation.setSupplierTel(gpReceiptGoodsUpdate.getSupplierTel());
                    gpSackInformation.setCustomer(gpReceiptGoodsUpdate.getCustomer());
                    gpSackInformation.setCustomerTel(gpReceiptGoodsUpdate.getCustomerTel());
                    gpSackInformation.setWarehousedNum(gpReceiptGoodsUpdate.getWarehousedNum());
                    gpSackInformation.setRemarks(gpReceiptGoodsUpdate.getRemarks());
                    gpSackInformation.setHoldOrNot(gpReceiptGoodsUpdate.getHoldOrNot());
                    iGpSackInformationService.save(gpSackInformation);
                }
            }
        }
        return true;
    }

    @Override
    public boolean copy(Long id, Integer copyNum) {
        GpSackInformation gpSackInformation = this.getById(id);
        if (gpSackInformation == null) {
            return false;
        }
        for (int i = 0; i < copyNum; i++) {
            gpSackInformation.setId(null);
            this.save(gpSackInformation);
        }
        return true;
    }

    @Override
    public GpCtnOrderExcel getString(Collection<?> coll, Object ob, InputStream inputStream, String fileName) throws IOException {
        GpCtnOrderExcel gpExcelTemplateUrl = new GpCtnOrderExcel();
        try {

            String filename = StringUtils.encodingFilename(fileName);
            String absoluteFile = StringUtils.getAbsoluteFile(filename);
            FileOutputStream outputStream = new FileOutputStream(absoluteFile);
            //从第几列合并
            int[] mergeColumnIndex = {1,2,3,5,6,7};
            // 需要从第几行开始合并
            int mergeRowIndex = 16;
            // 订单号
            int indexSn = 11;
            //设置输出流和模板信息
            ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream)
                    .registerWriteHandler(new ExcelFillCellMergeStrategy(mergeRowIndex,mergeColumnIndex))
                    .build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
//            writeSheet.setAutoMergeCell(true);
            //开启自动换行,自动换行表示每次写入一条list数据是都会重新生成一行空行,此选项默认是关闭的,需要提前设置为true
            if (CollectionUtils.isNotEmpty(coll)) {
                //横斜
//                FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build();
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                //设置自动合并单元格
                excelWriter.fill(coll, fillConfig, writeSheet);
            }
            excelWriter.fill(ob, writeSheet);
            excelWriter.finish();
            gpExcelTemplateUrl.setUrl(GpframeworkConfig.getPath() + filename);
            gpExcelTemplateUrl.setAbsoluteFile(absoluteFile);


            File file1 = new File(absoluteFile);
            FileInputStream file = new FileInputStream(file1);
            Workbook workbook=new XSSFWorkbook(file);
            Sheet sheet = workbook.getSheetAt(0);

            // 获取总行数
            int rowCount = sheet.getPhysicalNumberOfRows();

            // 定义正则表达式模式
            String regex = "-.*"; // 匹配 "-" 后的任意字符

            // 编译正则表达式
            Pattern pattern = Pattern.compile(regex);

            // 从第六行开始处理
            for (int i = 5; i < rowCount; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    // 对该行中的每个单元格进行处理
                    for (Cell cell : row) {
                        cell.setCellType(CellType.STRING);
                        String cellValue = cell.getStringCellValue();

                        // 使用正则表达式进行匹配
                        Matcher matcher = pattern.matcher(cellValue);
                        if (matcher.find()) {
                            // 找到匹配项，将 "-" 及其后内容替换为空字符串
                            String replacedValue = matcher.replaceAll("");
                            cell.setCellValue(replacedValue);
                        }
                    }
                }
            }

            file.close();

            FileOutputStream outFile = new FileOutputStream(absoluteFile);
            workbook.write(outFile);
            outFile.close();
            workbook.close();


            gpExcelTemplateUrl.setAbsoluteFile(absoluteFile);

            return gpExcelTemplateUrl;
        } catch (FileNotFoundException e) {
            log.error("生成excel错误：" + e);
            return null;
        }
    }
}
